package com.edu.service.impl;

import com.edu.bean.User;
import com.edu.mapper.UserMapper;
import com.edu.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 75099637@qq.com
 * @PackageName SpringAndMybatis
 * @Package com.edu.service.impl
 * @Date 2023/11/7 19:25
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public Map<String, Object> login(String username, String password) {
        Map<String, Object> map = new HashMap<>();
        User user = userMapper.selectUser(username, password);
        if (user != null) {
            map.put("loginUser", user);
        } else {
            user = userMapper.selectByUserName(username);
            if (user == null) {
                map.put("errorCode", "-1");
            } else {
                map.put("errorCode", "-2");
            }
        }
        return map;
    }

    @Override
    public int register(User user) {
        if (userMapper.selectByUserName(user.getUsername()) != null) {
            return -1;
        }
        return userMapper.insert(user);
    }

    @Override
    public int updatePassword(User user, String originalPassword) {
        if (userMapper.selectByUserName(user.getUsername()) == null) {
            return -1;
        } else if (userMapper.selectByUserName(user.getUsername()).getPassword() == originalPassword) {
            // 与原始密码不相等
            return -2;
        }
        return userMapper.updateByPrimaryKey(user);
    }

    @Override
    public List<User> getUserAll() {
        return userMapper.selectAll();
    }

    @Override
    public User getUserByUserName(String username) {
        return userMapper.selectByUserName(username);
    }
}
